package com.ruoyi.tester.executor.expression;

import com.ruoyi.tester.executor.ExpressionContext;
import org.json.JSONArray;
import org.springframework.stereotype.Component;

/**
 * @author SongJun
 * @description TODO:
 * @date 2022/4/27 10:12
 */
@Component
public class ExpAt implements ExpressionAnalysis {
    @Override
    public String getExpressionName() {
        return "at";
    }

    @Override
    public String getDescription() {
        return "at(n) 返回当前列表上下文第n个元素的值(序号n从0开始);";
    }

    @Override
    public Object analysis(ExpressionContext context, String... param) {
        JSONArray node;
        if(context.getContext() instanceof JSONArray){
            node = (JSONArray) context.getContext();
        } else if(context.getContext() instanceof String){
            node = new JSONArray((String)context.getContext());
        } else {
            node = new JSONArray(context.getContext());
        }
        String index = param[0];
        if (node != null || node.length() > Integer.valueOf(index)) {
            int pos;
            if(index.startsWith("-")){
                pos = Integer.valueOf(index) + node.length() - 1;
            } else {
                pos = Integer.valueOf(index);
            }
            return node.get(pos);
        } else {
            throw new RuntimeException("at("+param[0]+")依赖参数返回异常"+param[1]);
        }
    }
}
